Page({
  data: {
    contacts: [],
    currentContactId: null
  },

  onLoad() {
    this.loadContacts();
  },

  loadContacts() {
    wx.cloud.callFunction({
      name: 'getEmergencyContacts',
      success: (res) => {
        this.setData({
          contacts: res.result.data
        });
      }
    });
  },

  onAddContact() {
    wx.navigateTo({
      url: '/pages/user/emergency-edit'
    });
  },

  onEditContact(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/user/emergency-edit?id=${id}`
    });
  },

  onCall(e) {
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    });
  },

  onDeleteContact(e) {
    this.setData({
      currentContactId: e.currentTarget.dataset.id
    });
    this.selectComponent('#deleteDialog').show();
  },

  onConfirmDelete() {
    wx.cloud.callFunction({
      name: 'deleteEmergencyContact',
      data: {
        id: this.data.currentContactId
      },
      success: () => {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        this.loadContacts();
      }
    });
  }
});